<template>
	<view
		class="fast-lazy-load"
		@click="$emit('click')"
		:style="{
			width: !isNaN(width) ? width + 'rpx' : width,
			height: !isNaN(height) ? height + 'rpx' : height,
			'border-radius': !isNaN(radius) ? radius + 'rpx' : radius
		}"
	>
		<view v-if="loading" class="loading">
			<slot name="loading">
				<image
					class="lazy-image"
					src=""
				></image>
			</slot>
		</view>
		<view v-if="error" class="loading error">
			<slot name="error">
				<image
					class="lazy-image"
					src=""
				></image>
			</slot>
		</view>
		<image
			:src="src"
			:mode="mode"
			:class="{ show: !loading && !error }"
			:style="{
				width: !isNaN(width) ? width + 'rpx' : width,
				height: !isNaN(height) ? height + 'rpx' : height,
				'border-radius': !isNaN(radius) ? radius + 'rpx' : radius
			}"
			@load="load"
			@error="errorImg"
		></image>
	</view>
</template>

<script>
export default {
	name: 'fast-lazy-load',
	components: {},
	props: {
		/** 图片地址 **/
		src: String,
		/** 图片宽度 **/
		width: [Number, String],
		/** 图片高度 **/
		height: [Number, String],
		/** 图片裁剪、缩放的模式 **/
		mode: {
			type: String,
			default: 'aspectFill'
		},
		/** 图片圆角 **/
		radius: {
			type: [Number, String],
			default: 0
		}
	},
	data() {
		return {
			loading: true,
			error: false
		}
	},
	methods: {
		load() {
			setTimeout(() => {
				this.loading = false
				this.error = false
			}, 300)
		},
		errorImg() {
			setTimeout(() => {
				this.loading = false
				this.error = true
			}, 300)
		}
	},
	computed: {},
	filters: {},
	watch: {},
	created() {},
	mounted() {},
	activated() {}
}
</script>

<style scoped lang="scss">
.fast-lazy-load {
	display: inline-block;
	background: #f0f0f0;
	overflow: hidden;
	position: relative;
	.loading {
		width: 100%;
		height: 100%;
		display: inline-flex;
		justify-content: center;
		align-items: center;
		.lazy-image {
			max-width: 130rpx;
			max-height: 130rpx;
			width: 50%;
			height: 50%;
		}
	}
	& > image {
		transition: 0.3s opacity;
		opacity: 0;
		&.show {
			opacity: 1;
		}
	}
}
</style>
